#!/usr/bin/env python
# -*- coding:utf-8 -*-

import triangle

import os
import time
import random

class ElapseTime(object):
    def __init__(self, prompt):
        self.start = time.time()
        self.prompt = prompt
        
    def __del__(self):
        print ('%s耗时: %.3f' % (self.prompt, time.time() - self.start))

def test001(): 
    for name in (  #'square_circle_hole.1',
                 #'spiral.1',
                 #'spiral.q.1',
                 'A.1',
                 'A',
                 #'bbox.1',
                 #'box.1',
                 ):
        triangle.show_data(name)
    name = 'greenland'
    name = 'square_circle_hole.1'
    name = 'square_circle_hole'
    name = 'spiral.1'
    name = 'spiral.q.1'

def test002():
    import triangle
    import triangle.plot
    import matplotlib.pyplot as plt
    import numpy as np
    from yy3d.occ.topo import make_face_by_wire, make_wire_by_points
    from OCC.gp import gp_Pnt
    from OCC.Display.SimpleGui import init_display
    pts = np.array([[0, 0], [0, 1], [.5, .5], [1, 1], [1, 0]])
    pts = np.array([[1751.0066,  706.2925],
                    [2655.1142,  796.8993],
                    [3430.4045,  541.7697],
                    [4508.6542,  677.6798],
                    [4921.3472, 1385.8431],
                    [4756.7471, 2196.5351],
                    [4157.9845, 2010.5528],
                    [4229.5498, 1295.2364],
                    [3988.6134,  985.2659],
                    [3590.2335, 1061.5663],
                    [3029.6390, 1292.8520],
                    [2581.1635, 1147.4043],
                    [2049.1951, 1209.3984],
                    [2149.3865, 1762.5765],
                    [3144.1435, 2079.7001],
                    [3456.6450, 2547.0402],
                    [2807.7868, 2618.5718],
                    [1917.9922, 2520.8119],
                    [1646.0442, 1776.8828],
                    [1591.1775, 1152.1731],
                    ])
    tris = triangle.delaunay(pts)
    display, start_display, add_menu, add_function_to_menu = init_display(window_title = '桥梁组装')
    for tri in tris:
        points = [gp_Pnt(pts[i, 0], pts[i, 1], 0) for i in tri]
        face = make_face_by_wire(make_wire_by_points(points))
        display.DisplayShape(face)
    display.FitAll()
    start_display()
    
    #triangle.plot.plot(plt.axes(), vertices=pts, triangles=tri)
    #plt.show()

def test003():
    import triangle
    import numpy as np
    atimer = ElapseTime('数据初始化')
    pts = []
    for i in range(10000000):
        pts.append([10000000.0 * random.random(), 10000000.0 * random.random()])
    pts = np.array(pts)
    atimer = ElapseTime('三角化')
    tris = triangle.delaunay(pts)

def test004():
    import triangle
    import numpy as np
    from yy3d.occ.topo import make_face_by_wire, make_wire_by_points
    from OCC.gp import gp_Pnt
    from OCC.Display.SimpleGui import init_display
    atimer = ElapseTime('数据初始化')
    pts = [[1751.0066,  706.2925],
           [2655.1142,  796.8993],
           [3430.4045,  541.7697],
           [4508.6542,  677.6798],
           [4921.3472, 1385.8431],
           [4756.7471, 2196.5351],
           [4157.9845, 2010.5528],
           [4229.5498, 1295.2364],
           [3988.6134,  985.2659],
           [3590.2335, 1061.5663],
           [3029.6390, 1292.8520],
           [2581.1635, 1147.4043],
           [2049.1951, 1209.3984],
           [2149.3865, 1762.5765],
           [3144.1435, 2079.7001],
           [3456.6450, 2547.0402],
           [2807.7868, 2618.5718],
           [1917.9922, 2520.8119],
           [1646.0442, 1776.8828],
           [1591.1775, 1152.1731],
           ]
    segs = [(0, i) for i in range(1, len(pts))]
    segs.append((len(pts) - 1, 0))
    vertex_markers = [1] * len(pts)
    segment_markers = [1] * len(segs)
    
    pts.extend([[1798.7167  ,947.1157],
                [3001.5508  ,948.0336],
                [4410.8484  ,854.1246],])
    ns = len(pts) - 3
    vertex_markers.extend((0, 0, 0))
    segs.extend([(ns, ns + 1),
                 [ns + 1, ns + 2]])
    segment_markers.extend((0, 0))
    
    atimer = ElapseTime('三角化')
    tris = triangle.triangulate({'vertices': pts,
                                 'segments': segs,
                                 'vertex_markers':  vertex_markers,
                                 'segment_markers': segment_markers,
                                 #'holes': [[2683.7403  ,1464.5279],],
                                 }, 'p')
    tris_indexes = tris['triangles']
    print(len(tris_indexes))
    display, start_display, add_menu, add_function_to_menu = init_display(window_title = '桥梁组装')
    pts = np.array(pts)
    pts = tris['vertices']
    for tri in tris_indexes:
        points = [gp_Pnt(pts[i, 0], pts[i, 1], 0) for i in tri]
        face = make_face_by_wire(make_wire_by_points(points))
        display.DisplayShape(face)
    display.FitAll()
    start_display()    

def get_data_file(name):
    datadir = os.path.join(os.path.dirname(__file__), 'triangle', 'data')
    assert os.path.isdir(datadir)
    filename = os.path.join(datadir, name)
    assert os.path.isfile(filename)
    return filename

def parse_count(string_data: str) -> int:
    return int(string_data.strip().split()[0])

def parse_point(string_data: str):
    return [float(i) for i in string_data.strip().split()[1:3]]

def parse_segment(string_data: str):
    return [int(i)-1 for i in string_data.strip().split()[1:3]]

class PolyFile(object):
    def __init__(self, filename):
        assert os.path.isfile(filename)
        self.filename = filename
        content = ''
        with open(filename) as fp:
            content = fp.read()
        rows = [row for row in content.split('\n') if not row.lstrip().startswith('#')]
        vertex_count = parse_count(rows[0])
        rows = rows[1:]
        self.vertexs = [parse_point(pt) for pt in rows[:vertex_count]]
        if 0:
            print('pl')
            for vertex in self.vertexs:
                print('%s,%s' % tuple(vertex), sep= ',')
        header = rows[vertex_count]
        rows = rows[vertex_count+1:]
        seg_count = parse_count(header)
        self.segs = [parse_segment(seg) for seg in rows[:seg_count]]
        for seg in self.segs:
            print('l')
            #print(seg)
            print('%s,%s' % tuple(self.vertexs[seg[0]]), sep= ',')
            print('%s,%s\n' % tuple(self.vertexs[seg[1]]), sep= ',')
        

def test005():
    import triangle
    import numpy as np
    import os
    from yy3d.occ.topo import make_face_by_wire, make_wire_by_points
    from OCC.gp import gp_Pnt
    from OCC.Display.SimpleGui import init_display
    atimer = ElapseTime('数据初始化')
    name = 'a.poly'
    name = 'yy.poly'
    name = 'box2.poly'
    apolyfile = PolyFile(get_data_file(name))
    #return
    atimer = ElapseTime('三角化')
    tris = triangle.triangulate({'vertices': apolyfile.vertexs,
                                 'segments': apolyfile.segs,
                                 #'vertex_markers':  vertex_markers,
                                 #'segment_markers': segment_markers,
                                 #'holes': [[2683.7403  ,1464.5279],],
                                 }    , 'p')
    tris_indexes = tris['triangles']
    print(len(tris_indexes))
    display, start_display, add_menu, add_function_to_menu = init_display(window_title = '桥梁组装')
    pts = tris['vertices']
    for tri in tris_indexes:
        points = [gp_Pnt(pts[i, 0], pts[i, 1], 0) for i in tri]
        face = make_face_by_wire(make_wire_by_points(points))
        display.DisplayShape(face)
    display.FitAll()
    start_display()    


if __name__ == '__main__':
    test005()